package com.ljx.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.ljx.utils.JwtUtil;
import com.ljx.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author LJX
 * @Description: TODO
 * @Date: 2023/2/23 19:50
 * @Version 1.0
 */
@Component
public class GatewayFilter implements GlobalFilter, Ordered {

	@Autowired
	private StringRedisTemplate redisTemplate;

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		// 1获取请求对象和相应对象
		ServerHttpRequest request = exchange.getRequest();
		ServerHttpResponse response = exchange.getResponse();
		// 2获取请求路径
		String path = request.getPath().toString();

		if ("/login".equals(path)){

			return chain.filter(exchange);

		}
		if("/system/user/sms".equals(path) || "/system/user/signInsert".equals(path)
		|| "/vip/api/home/zone/prefecture".equals(path) || "/vip/api/home/zoneBusiness/selectZoneBusiness".equals(path)
		|| "/vip/api/home/banner/rotationalSeeding".equals(path) || "/commodity/UB/goods/select".equals(path)
		|| "/commodity/UB/goods/selectB".equals(path) || "/system/home/bottomArticle/getQianAllBottomArticle".equals(path)
		|| "/system/home/link/getQianLink".equals(path) || "/system/home/zoneBusiness/findBusinessByName".equals(path)
		|| "/system/home/headNav/headNavigation".equals(path) || "/commodity/UB/business/selectAllZoneBusiness".equals(path)
		){
			return chain.filter(exchange);
		}
		// 3 获取请求头
		String token = request.getHeaders().getFirst("token");

		if(StringUtils.hasText(token)&& JwtUtil.verifyToken(token)&&redisTemplate.hasKey(token)){
			// 刷新token时间
			redisTemplate.expire(token,1, TimeUnit.DAYS);
			// 放行
			return chain.filter(exchange);
		}
		System.out.println(token);
		Result<String> result=new Result<>(5001,"登录失效");
		//3.3作JSON转换
		byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);

		//3.4调用bufferFactory方法,生成DataBuffer对象
		DataBuffer buffer = response.bufferFactory().wrap(bytes);

		//4.调用Mono中的just方法,返回要写给前端的JSON数据
		return response.writeWith(Mono.just(buffer));
	}

	@Override
	public int getOrder() {
		return 0;
	}
}
